import React, { useState, useRef, useEffect } from 'react';
import { Input, Button } from 'antd';
const { TextArea } = Input;

const HighlightTextArea = () => {
  const [value, setValue] = useState('');
  const textareaRef = useRef(null);
  const highlightsRef = useRef(null);

  // 需要高亮的关键词列表
  const highlightWords = ['重要', '紧急', 'TODO'];

  // 生成高亮HTML
  const getHighlightedHTML = (text) => {
    const regex = new RegExp(`(${highlightWords.join('|')})`, 'gi');
    return highlightWords.reduce((acc, cur) => {
      console.log(acc, cur);
      return acc.replace(
        regex,
        '<span class="highlight" style="background-color: red;">$1</span>',
      );
    }, text);
    // return text.replace(regex, '<mark class="highlight">$1</mark>');
  };

  // 同步滚动和高亮
  useEffect(() => {
    const syncScroll = () => {
      if (highlightsRef.current && textareaRef.current) {
        highlightsRef.current.scrollTop = textareaRef.current.scrollTop;
        highlightsRef.current.scrollLeft = textareaRef.current.scrollLeft;
      }
    };

    const textarea = textareaRef.current.resizableTextArea.textArea;
    textarea.addEventListener('scroll', syncScroll);
    return () => textarea.removeEventListener('scroll', syncScroll);
  }, []);

  return (
    <div style={{ position: 'relative', width: '100%' }}>
      {/* 高亮层 */}
      <div
        ref={highlightsRef}
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          zIndex: 1,
          pointerEvents: 'none',
          whiteSpace: 'pre-wrap',
          overflow: 'hidden',
          color: 'transparent',
          fontFamily: 'inherit',
          fontSize: '14px',
          lineHeight: '1.5',
          padding: '5px 11px', // 与antd TextArea内边距一致
        }}
        dangerouslySetInnerHTML={{ __html: getHighlightedHTML(value) }}
      />

      {/* 输入层 */}
      <TextArea
        ref={textareaRef}
        value={value}
        onChange={(e) => setValue(e.target.value)}
        style={{
          position: 'relative',
          zIndex: 2,
          backgroundColor: 'transparent',
        }}
        autoSize={{ minRows: 4 }}
      />
      <Button onClick={() => console.log(value)}>点击我老婆</Button>
    </div>
  );
};

export default HighlightTextArea;
